using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using CodRevit.ViewModels;
using CodRevit.Views;
using CodRevit.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CodRevit.Commands
{
    /// <summary>
    /// 修改族类别命令
    /// 允许用户批量修改选中族的类别
    /// </summary>
    [Transaction(TransactionMode.Manual)]
    public class ChangeCategoryCommand : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                // 获取当前文档和界面应用程序
                UIApplication uiapp = commandData.Application;
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document doc = uidoc.Document;

                // 检查是否为项目文档
                if (doc.IsFamilyDocument)
                {
                    TaskDialog.Show("错误", "此命令只能在项目文档中使用。");
                    return Result.Failed;
                }

                // 选择族实例
                ICollection<ElementId> selectedIds;
                try
                {
                    selectedIds = uidoc.Selection.PickObjects(
                        ObjectType.Element,
                        new FamilyInstanceSelectionFilter(),
                        "请选择族实例").Select(r => r.ElementId).ToList();
                }
                catch (Autodesk.Revit.Exceptions.OperationCanceledException)
                {
                    return Result.Cancelled;
                }

                if (selectedIds.Count == 0)
                {
                    TaskDialog.Show("提示", "未选择任何族实例。");
                    return Result.Cancelled;
                }

                // 获取选中的族实例
                var familyInstances = selectedIds
                    .Select(id => doc.GetElement(id))
                    .OfType<FamilyInstance>()
                    .Where(fi => !fi.Symbol.Family.IsInPlace) // 过滤掉就地族
                    .ToList();

                if (!familyInstances.Any())
                {
                    TaskDialog.Show("提示", "选中的元素中没有有效的族实例。");
                    return Result.Cancelled;
                }

                // 创建ExternalEvent和Handler
                var categoryHandler = new ChangeCategoryHandler(uiapp);
                var externalEvent = ExternalEvent.Create(categoryHandler);

                // 创建窗口和ViewModel，传入预选择的族实例
                var window = new ChangeCategoryView();
                var viewModel = new ChangeCategoryViewModel(uiapp, externalEvent, categoryHandler, familyInstances);

                window.DataContext = viewModel;

                var positionedWindow = App.LeftTopWindow(commandData, window);
                if (positionedWindow == null || positionedWindow is not ChangeCategoryView)
                {
                    return Result.Failed;
                }
                window = (ChangeCategoryView)positionedWindow;
                window.Show();
                return Result.Succeeded;
            }
            catch (Exception ex)
            {
                TaskDialog.Show("错误", $"执行命令时发生错误：{ex.Message}");
                return Result.Failed;
            }
        }
    }
}